<template>
  <div class="student-score-display">
    <el-container>


      <!-- 主要内容区域 -->
      <el-main class="main">
        <!-- 统计卡片区域 -->
        <el-row :gutter="24" class="stats-row">
          <el-col :span="statsRowColSpan">
            <el-card class="stat-card gpa-card">
              <div class="stat-card-content">
                <div class="stat-icon"><i class="el-icon-s-data"></i></div>
                <div class="stat-info">
                  <div class="stat-label">平均绩点</div>
                  <div class="stat-value">{{ avgGPA.toFixed(2) }}</div>
                  <div class="stat-desc" :class="gpaTrendClass">
                    <i :class="gpaTrendIcon"></i>
                    <span>{{ gpaTrendText }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="statsRowColSpan">
            <el-card class="stat-card score-card">
              <div class="stat-card-content">
                <div class="stat-icon"><i class="el-icon-s-marketing"></i></div>
                <div class="stat-info">
                  <div class="stat-label">平均成绩</div>
                  <div class="stat-value">{{ avgScore.toFixed(2) }}</div>
                  <div class="stat-desc" :class="scoreTrendClass">
                    <i :class="scoreTrendIcon"></i>
                    <span>{{ scoreTrendText }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="statsRowColSpan">
            <el-card class="stat-card credit-card">
              <div class="stat-card-content">
                <div class="stat-icon"><i class="el-icon-s-finance"></i></div>
                <div class="stat-info">
                  <div class="stat-label">总学分</div>
                  <div class="stat-value">{{ totalCredits }}</div>
                  <div class="stat-desc" :class="creditTrendClass">
                    <i :class="creditTrendIcon"></i>
                    <span>{{ creditTrendText }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 合并后的查询+表格区域 -->
        <el-row class="combined-section">
          <el-col :span="24">
            <el-card class="combined-card">
              <!-- 成绩查询区域 -->
              <div class="query-section">
                <div class="query-header">
                  <span>成绩查询</span>
                  <el-tooltip effect="dark" content="可查询近4个学期成绩" placement="right">
                    <i class="el-icon-question-circle"></i>
                  </el-tooltip>
                </div>
                <el-form :inline="true" class="query-form">
                  <el-form-item label="学期" class="form-item-semester">
                    <el-select
                        v-model="query.semester"
                        placeholder="选择学期"
                        class="semester-select"
                        style="width: 220px;"
                    >
                      <el-option
                          v-for="semesterCode in semesters"
                          :key="semesterCode"
                          :label="semesterDict[semesterCode]"
                          :value="semesterCode"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item class="form-item-search">
                    <el-input
                        v-model="query.search"
                        placeholder="输入课程名称或课程编号..."
                        clearable
                        prefix-icon="el-icon-search"
                        @keyup.enter.native="fetchScores"
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="fetchScores" class="btn-query">
                      <i class="el-icon-search"></i> 查询
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 成绩表格区域 -->
              <div class="table-section">
                <div class="table-header">
                  <span>成绩列表</span>
                  <span class="table-count">共 {{ scores.length }} 门课程</span>
                </div>
                <el-table
                    :data="displayScores"
                    style="width: 100%"
                    border
                    stripe
                    highlight-current-row
                    :header-cell-style="headerCellStyle"
                    :row-class-name="tableRowClassName"
                    class="table-card"
                >
                  <el-table-column prop="courseCode" label="课程编号" min-width="120"></el-table-column>
                  <el-table-column prop="courseName" label="课程名称" min-width="180"></el-table-column>
<!--                  <el-table-column prop="credits" label="学分" min-width="80"></el-table-column>-->
                  <el-table-column label="课程性质" min-width="120">
                    <template #default="scope">
                      <el-tag :type="getCourseNatureTag(scope.row.courseNature)">
                        {{ courseNatureDict[scope.row.courseNature] || '未知' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="总成绩" min-width="100">
                    <template #default="scope">
                    <span :class="getScoreClass(scope.row.totalScore)">
                      {{ scope.row.totalScore.toFixed(2) }}
                    </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="gradePoint" label="绩点" min-width="80"></el-table-column>
                  <el-table-column label="补考成绩" min-width="100">
                    <template #default="scope">
                      <span>{{ scope.row.resitScore !== null ? scope.row.resitScore.toFixed(2) : '-' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="学期" min-width="120">
                    <template #default="scope">
                      {{ semesterDict[scope.row.semester] || '未知' }}
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 分页组件 -->
                <div class="pagination-container" v-if="scores.length > 0">
                  <el-pagination
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="currentPage"
                      :page-sizes="[4]"
                      :page-size="pageSize"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="scores.length">
                  </el-pagination>
                </div>

                <div v-if="scores.length === 0" class="empty-state">
                  <el-empty description="暂无成绩数据"></el-empty>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue';
// 引入封装的 API 函数
import { getStudentScores, getScoreStats, getUserInfo } from '@/api/trainingManagement/studentScore';

export default {
  name: 'StudentScoreDisplay',
  setup() {
    // 学生信息（动态获取）
    const studentName = ref('');

    // 统计数据（后端 StudentScoreStatsVO 对应字段）
    const avgGPA = ref(0);        // 对应 avgGradePoint
    const avgScore = ref(0);      // 对应 avgTotalScore
    const totalCredits = ref(0);  // 对应 totalCredits

    // 查询参数（学期用后端编码）
    const query = ref({
      search: '',
      semester: null, // 初始为空（显示全部），后端 semester 为 Integer
    });

    // 学期配置（与后端 semester 编码一致）
    const semesters = ref([1, 2]); // 后端返回的 semester 是 1/2
    const semesterDict = {
      1: '2023-2024学年 第一学期',
      2: '2023-2024学年 第二学期',
    };

    // 成绩列表（后端 StudentScoreVO 数组）
    const scores = ref([]);
    const originalScores = ref([]); // 缓存原始数据，用于筛选重置

    // 课程性质字典（与后端 courseNature 编码一致）
    const courseNatureDict = {
      1: '专业必修课',
      2: '公共必修课',
      3: '专业选修课',
      4: '实践环节',
      5: '公共选修课',
    };

    // 分页相关变量
    const currentPage = ref(1);      // 当前页码
    const pageSize = ref(6);         // 每页条数
    const displayScores = ref([]);   // 当前页显示的数据

    // 加载用户信息
    const fetchUserInfo = async () => {
      try {
        const res = await getUserInfo();
        if (res.code === 200) {
          // 优先取昵称，无则取用户名，否则显示"未知用户"
          studentName.value = res.data.nickName || res.data.userName || '未知用户';
        }
      } catch (error) {
        console.error('获取用户信息失败：', error);
        studentName.value = '未知用户';
      }
    };

    // 加载成绩数据
    const fetchData = async () => {
      try {
        // 1. 获取当前用户信息（需包含 studentId）
        const userRes = await getUserInfo();
        const userInfo = userRes.data;
        // const studentId = userInfo.studentId; // 提取与 course_student_info.student_id 一致的字段
        // console.log("前端传递的学生标识：", studentId); // 验证是否为 7d007e...
        const userName = userInfo.userName; // 学号：107622025210830
        console.log("前端传递的学号：", userName);



        // 2. 传递 studentId 查询成绩列表
        // const scoreRes = await getStudentScores(studentId);
        const scoreRes = await getStudentScores(userName);
        if (scoreRes.code === 200) {
          scores.value = scoreRes.params.data || []; // 从params.data取成绩列表
          originalScores.value = [...scores.value];
        }

        // 3. 传递 studentId 查询成绩统计
        // const statsRes = await getScoreStats(studentId);
        const statsRes = await getScoreStats(userName);
// 修改后
        if (statsRes.code === 200) {
          avgGPA.value = statsRes.params.data.avgGradePoint || 0; // 从params.data取统计数据
          avgScore.value = statsRes.params.data.avgTotalScore || 0;
          totalCredits.value = statsRes.params.data.totalCredits || 0;
        }
      } catch (error) {
        console.error('数据加载失败：', error);
        ElMessage.error('数据加载失败，请重试');
      }
    };
    // 筛选逻辑
    const fetchScores = () => {
      let filtered = [...originalScores.value];
      if (query.value.search) {
        filtered = filtered.filter(score =>
            score.courseName?.includes(query.value.search) ||
            score.courseCode?.includes(query.value.search)
        );
      }
      if (query.value.semester !== null) {
        filtered = filtered.filter(score => score.semester === query.value.semester);
      }
      scores.value = filtered;
      currentPage.value = 1; // 筛选后回到第一页
    };

    // 分页逻辑：监听数据变化，重新计算当前页数据
    watch([scores, currentPage, pageSize], () => {
      const startIndex = (currentPage.value - 1) * pageSize.value;
      const endIndex = startIndex + pageSize.value;
      displayScores.value = scores.value.slice(startIndex, endIndex);
    }, { immediate: true }); // 初始加载时立即执行

    // 页码变化事件
    const handleCurrentChange = (val) => {
      currentPage.value = val;
    };

    // 每页条数变化事件
    const handleSizeChange = (val) => {
      pageSize.value = val;
      currentPage.value = 1; // 切换每页条数后回到第一页
    };

    // 日期格式化
    const formatDate = (date) => {
      const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
      return date.toLocaleDateString('zh-CN', options);
    };

    // 表格样式
    const headerCellStyle = {
      'background-color': '#f5f7fa',
      'font-weight': 'bold',
      'color': '#303133'
    };

    const tableRowClassName = ({ rowIndex }) => {
      return rowIndex % 2 === 0 ? 'row-even' : 'row-odd';
    };

    // 成绩颜色样式
    const getScoreClass = (score) => {
      if (score >= 90) return 'score-excellent';
      if (score >= 80) return 'score-good';
      if (score >= 60) return 'score-passed';
      return 'score-failed';
    };

    // 课程性质标签样式
    const getCourseNatureTag = (natureCode) => {
      switch (natureCode) {
        case 1: return 'primary';   // 专业必修课
        case 2: return 'success';   // 公共必修课
        case 3: return 'info';      // 专业选修课
        case 4: return 'warning';   // 实践环节
        case 5: return 'info';      // 公共选修课
        default: return 'default';
      }
    };

    // 趋势数据
    const gpaTrendClass = ref('trend-up');
    const gpaTrendIcon = ref('el-icon-caret-top');
    const gpaTrendText = ref('较上学期提升0.2');

    const scoreTrendClass = ref('trend-up');
    const scoreTrendIcon = ref('el-icon-caret-top');
    const scoreTrendText = ref('较上学期提升3.5分');

    const creditTrendClass = ref('trend-up');
    const creditTrendIcon = ref('el-icon-caret-top');
    const creditTrendText = ref('已完成毕业要求的40%');

    // 响应式布局：统计卡片列数
    const statsRowColSpan = computed(() => {
      if (window.innerWidth <= 768) return 24;
      if (window.innerWidth <= 1024) return 12;
      return 8;
    });

    // 页面初始化
    onMounted(() => {
      fetchUserInfo(); // 先获取用户信息
      fetchData();     // 再获取成绩数据
      window.addEventListener('resize', () => statsRowColSpan.value);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', () => statsRowColSpan.value);
    });

    // 返回值
    return {
      studentName, avgGPA, avgScore, totalCredits, query, scores, semesters,
      semesterDict, courseNatureDict, fetchScores, formatDate, headerCellStyle,
      tableRowClassName, getScoreClass, getCourseNatureTag, gpaTrendClass,
      gpaTrendIcon, gpaTrendText, scoreTrendClass, scoreTrendIcon, scoreTrendText,
      creditTrendClass, creditTrendIcon, creditTrendText, statsRowColSpan,
      displayScores, currentPage, pageSize, handleCurrentChange, handleSizeChange
    };
  },
};
</script>

<style scoped>
/* 样式部分完全不变 */
.student-score-display {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 头部样式 */
.header {
  background-color: #2c3e50;
  color: #fff;
  padding: 0 20px;
  height: 60px !important;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header-content {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.system-title {
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border: 2px solid rgba(255, 255, 255, 0.2);
}

.welcome-text {
  font-size: 14px;
}

.current-date {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

.divider {
  height: 20px;
  background-color: rgba(255, 255, 255, 0.2);
}

/* 主内容区 */
.main {
  padding: 20px;
  background-color: #f5f7fa;
}

/* 统计卡片样式 */
.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  border: none;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stat-card-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: #fff;
}

.gpa-card .stat-icon {
  background-color: #409eff;
}

.score-card .stat-icon {
  background-color: #67c23a;
}

.credit-card .stat-icon {
  background-color: #e6a23c;
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1.2;
}

.stat-desc {
  font-size: 13px;
  margin-top: 8px;
  display: flex;
  align-items: center;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

/* 查询区域样式 */
.query-row {
  margin-bottom: 24px;
}

.query-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.query-header {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.query-header .el-icon-question-circle {
  color: #409eff;
  cursor: pointer;
}

.query-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.form-item-semester .el-form-item__label {
  color: #606266;
  font-weight: 500;
}

.semester-select .el-input__inner {
  width: 220px;
  border-radius: 4px;
  transition: border-color 0.2s;
}

.semester-select .el-input__inner:focus {
  border-color: #409eff;
}

.form-item-search .el-input {
  width: 300px;
}

.form-item-search .el-input__inner {
  border-radius: 4px 0 0 4px;
}

.btn-query, .btn-export {
  transition: all 0.2s;
  padding: 10px 20px;
}

.btn-query {
  border-radius: 0 4px 4px 0;
}

.btn-query:hover, .btn-export:hover {
  transform: translateY(-2px);
}

/* 表格区域样式 */
.table-row {
  margin-bottom: 20px;
}

.table-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 0 5px;
}

.table-header span:first-child {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-count {
  font-size: 13px;
  color: #606266;
}

.el-table {
  border-radius: 4px;
  overflow: hidden;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: 600;
}

.el-table tr:hover > td {
  background-color: #f0f7ff !important;
}

.row-even {
  background-color: #fafafa;
}

.row-odd {
  background-color: #fff;
}

/* 成绩样式 */
.score-excellent {
  color: #67c23a;
  font-weight: 500;
}

.score-good {
  color: #409eff;
  font-weight: 500;
}

.score-passed {
  color: #e6a23c;
}

.score-failed {
  color: #f56c6c;
  font-weight: 500;
}

/* 空状态样式 */
.empty-state {
  padding: 40px 0;
  text-align: center;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .form-item-search .el-input {
    width: 200px;
  }
  .stats-row .el-col {
    margin-bottom: 15px;
  }
}
/* 学期选择框宽度强化（防止被覆盖） */
.semester-select .el-input__inner {
  width: 220px !important;
  border-radius: 4px;
}


.table-header {
  padding: 0 20px; /* 增加内边距，避免文字贴边 */
}
@media (max-width: 768px) {
  .query-form {
    flex-direction: column;
    align-items: flex-start;
  }
  .form-item-search .el-input {
    width: 100%;
  }
  .system-title {
    display: none;
  }
  .header-content {
    justify-content: flex-end;
  }
  .stats-row .el-col {
    margin-bottom: 15px;
  }
}

/* 合并区域的容器样式 */
.combined-section {
  margin-bottom: 20px; /* 与统计卡片保持间距 */
}

/* 合并后的 Card 样式：统一背景和阴影 */
.combined-card {
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: none;
}

/* 查询区域内部样式：增加分隔线 */
.query-section {
  padding: 20px;
  border-bottom: 1px solid #ebeef5; /* 与表格区域分隔 */
}

/* 表格区域内部样式：去掉默认间距 */
.table-section {
  padding: 20px;
}
/* 确保表格卡片撑满宽度 */
.table-card {
  width: 100% !important;
  max-width: none !important;
}

/* 分页组件样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 15px;
  padding: 10px 0;
}

/* 表格样式微调（确保分页与表格间距） */
.el-table {
  margin-bottom: 10px;
}
</style>
